/**
 * @author 陈泰来
 * @version V1.0
 * @Project ioex
 * @Title 多路复用类
 * @Description *
 * @Package com.echo.ioex.nio.server.ext
 * @date 2020/9/23 1:22 下午
 * @Copyright: 陈泰来の学习档案 .
 */
package com.echo.ioex.nio.server.ext;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

@Slf4j
public class MultiplexerTimeServer implements Runnable {

    /**
     * @description 多路复用器 @author chentl @date 2020/9/23 1:23 下午
     **/
    private Selector selector;

    private ServerSocketChannel serverSocketChannel;

    private volatile boolean stop;

    public MultiplexerTimeServer(int port) {
        try {
            //创建多路复用器
            selector = Selector.open();
            //创建ServerSocketChannel
            serverSocketChannel = ServerSocketChannel.open();
            //设置端口 + 地址
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.socket().bind(new InetSocketAddress(port), 1024);
            //将Channel注册到Selector上
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            log.info("NIO 服务端已在 {} 端口启动", port);
        } catch (IOException e) {
            log.error("初始化多路复用器异常", e);
            //资源初始化失败 则退出
            System.exit(1);
        }
    }

    @Override
    public void run() {
        //无限执行  直到停止
        while (!stop) {
            try {
                //每隔一秒
                selector.select(1000);
                Set<SelectionKey> selectionKeySet = selector.selectedKeys();
                Iterator<SelectionKey> it = selectionKeySet.iterator();
                SelectionKey key;
                //无限循环 selector 中的所有key
                while (it.hasNext()) {
                    key = it.next();
                    it.remove();

                    handleInput(key);
                }
            } catch (IOException e) {
                log.error("多路复用器获取就绪的Channel时出现异常", e);
            }
        }


    }

    /**
     * @return void
     * @author chentl
     * @description 处理接收的数据
     * @date 2020/9/24 12:57 下午
     * @params [key]
     */
    private void handleInput(SelectionKey key) throws IOException {

        if (key.isValid()) {
            //新的接入是否就绪
            if (key.isAcceptable()) {
                //接收新请求
                ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                SocketChannel sc = ssc.accept();
                sc.configureBlocking(false);
                //注册新连接到多路复用器上
                sc.register(selector, SelectionKey.OP_READ);

            }

            //消息是否可读
            if (key.isReadable()) {
                SocketChannel sc = (SocketChannel) key.channel();
                //开辟1k内存 存储数据
                ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                //读取
                int readBytes = sc.read(readBuffer);
                if (readBytes > 0) {
                    //翻转 将指针位置翻转到初始位置，然后
                    readBuffer.flip();
                    byte[] bytes = new byte[readBuffer.remaining()];
                    readBuffer.get(bytes);
                    String body = new String(bytes, StandardCharsets.UTF_8);
                    log.info("时间服务器收到请求:{}", body);
                    String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER";
                    doWrite(sc, currentTime);

                } else if (readBytes < 0) {
                    //对端链路关闭
                    key.cancel();
                    sc.close();
                } else log.info("读到0字节，忽略");

            }
        }

    }

    /**
    * @author chentl
    * @description 写消息
    * @date 2020/9/24 1:00 下午
    * @params [channel, response]
    * @return void
    */
    private void doWrite(SocketChannel channel, String response) throws IOException {
        if (response != null && response.trim().length() > 0) {
            byte[] bytes = response.getBytes();
            ByteBuffer writterBuffer = ByteBuffer.allocate(bytes.length);
            writterBuffer.put(bytes);
            writterBuffer.flip();
            channel.write(writterBuffer);
        }
    }

    /**
    * @author chentl
    * @description 停止
    * @date 2020/9/24 1:00 下午
    * @params []
    * @return void
    */
    public void stop() {
        this.stop = true;
    }
}
